//
//  BaseThemeViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/27.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "BaseThemeViewController.h"
#import "NavBarView.h"
#import "ThemeEditorsViewController.h"
#import "ThemesModel.h"
#import "ThemeContentModel.h"
#import "ThemeCell.h"
#import "ThemeEditorModel.h"
#import <MJExtension/MJExtension.h>
#import <MJRefresh/MJRefresh.h>
#import "NetworkingTool.h"
#import "NewsListModel.h"
#import "NewsDetailViewController.h"
#import "MainNavigationController.h"
#import "UIImageView+WebCache.h"
#import "RefreshProgressView.h"
#import "UIImageView+LBBlurredImage.h"
#import "SQLiteManager.h"

@interface BaseThemeViewController () <UITableViewDataSource, UITableViewDelegate>
{
    CGFloat _topImageH;
}
/** story模型数组 */
@property (nonatomic, strong) NSMutableArray *stories;

/** 主编模型数组 */
@property (nonatomic, strong) NSMutableArray *editors;

/** 主题内容模型 */
@property (nonatomic, strong) ThemeContentModel *contentModel;

/** tableView */
@property (nonatomic, weak) UITableView *tableView;

/** 自定义导航栏 */
@property (nonatomic, weak) NavBarView *navBarView;

/** 顶部图片 容器view */
@property (nonatomic, weak) UIImageView *topImageContainerViewView;

/** 顶部图片 */
@property (nonatomic, weak) UIImageView *topImageView;

/** 顶部图片 上面的模糊图片 */
@property (nonatomic, weak) UIImageView *topCoverImageView;

/** toolbBar，用于模糊效果 */
@property (nonatomic, weak) UIToolbar *toolBar;

/** 顶部图片高度 */
@property (nonatomic, assign, readonly) CGFloat topImageH;

/** 刷新控件 */
@property (nonatomic, weak) RefreshProgressView *refreshView;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;

/** tableHeaderView */
@property (nonatomic, weak) UIView *headerContainerView;

/** tableHeaderView上的label */
@property (nonatomic, weak) UILabel *headerLabel;

/** 重新加载按钮 */
@property (nonatomic, weak) UIButton *reloadBtn;
@end

@implementation BaseThemeViewController

static NSString *themeReuseID = @"themeCell";

#pragma mark - 懒加载
- (UIButton *)reloadBtn{
    if (!_reloadBtn) {
        UIButton *reloadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        reloadBtn.backgroundColor = JKGlobalBgColor;
        reloadBtn.titleLabel.numberOfLines = 0;
        reloadBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        reloadBtn.hidden = YES;
        [reloadBtn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [reloadBtn setTitle:@"加载数据，点击重新加载" forState:(UIControlStateNormal)];
        [reloadBtn addTarget:self action:@selector(loadNewLists) forControlEvents:(UIControlEventTouchUpInside)];
        [self.view insertSubview:reloadBtn belowSubview:self.navBarView];
        _reloadBtn = reloadBtn;
    }
    return _reloadBtn;
}

- (RefreshProgressView *)refreshView{
    if (!_refreshView) {
        RefreshProgressView *refreshView = [[RefreshProgressView alloc] init];
        refreshView.backgroundColor = [UIColor clearColor];
        refreshView.frame = CGRectMake((JKScreenW - [self calculateTitleWidth]) * 0.5 - 32, 33, 24, 24);
        refreshView.centerY = self.navBarView.defaltCenter.y;
        [self.view addSubview:refreshView];
        _refreshView = refreshView;
    }
    return _refreshView;
}

- (CGFloat)topImageH{
    if (!_topImageH) {
        _topImageH = JKScreenW * 0.38;
    }
    return _topImageH;
}

- (NSMutableArray *)stories{
    if (!_stories) {
        _stories = [NSMutableArray array];
    }
    return _stories;
}

- (NSMutableArray *)editors{
    if (!_editors) {
        _editors = [NSMutableArray array];
    }
    return _editors;
}

- (CGFloat)calculateTitleWidth{
    
    //计算文字的高度
    CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
    
    //评论内容高度
    return [self.themeModel.name boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:18]} context:nil].size.width;
}

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self setupNavBar];
    
    [self setupTableView];
    
    [self setupTopImageView];
    
    [self setupRefresh];
}

- (void)setThemeModel:(ThemesModel *)themeModel{
    _themeModel = themeModel;
    
    self.tableView.backgroundColor = self.view.backgroundColor;
    
    [_stories removeAllObjects];
    [_tableView reloadData];
    
    for (UIView *subV in self.headerContainerView.subviews) {
        
        if ([subV isKindOfClass:[UIImageView class]]) {
            
            [subV removeFromSuperview];
        }
    }
    
//    [_tableView setContentOffset:CGPointMake(0, -_tableView.contentInset.top) animated:NO];
//    [_tableView layoutIfNeeded];
    
    self.navBarView.title = self.themeModel.name;
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.topImageView.alpha = 0;
    }];
}

- (void)setupNavBar{
    
    NavBarView *navBarView = [NavBarView barViewWithTitle:self.themeModel.name showBackTitle:NO];
    [navBarView changeToDaySkinWithBgAlpha:0];
    __weak typeof(self) weakSelf = self;
    [navBarView setBackBtnClickBlock:^(UIButton *btn) {
        MainNavigationController *mainNav = (MainNavigationController *)weakSelf.navigationController;
        !mainNav.showLeftVcBlock ? : mainNav.showLeftVcBlock();
    }];
    [self.view addSubview:navBarView];
    self.navBarView = navBarView;
}

- (void)setupTableView{
    
    UITableView *tableView = [[UITableView alloc] init];
    tableView.frame = CGRectMake(0, JKNavBarHeight, self.view.width, self.view.height - JKNavBarHeight);
    [tableView jk_adapt_iOS_11_scrollView];
    tableView.backgroundColor = self.view.backgroundColor;
    tableView.rowHeight = 80;
    tableView.dataSource = self;
    tableView.delegate = self;
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ThemeCell class]) bundle:nil] forCellReuseIdentifier:themeReuseID];
    [self.view insertSubview:tableView belowSubview:self.navBarView];
    self.tableView = tableView;
    
    tableView.tableFooterView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, JKScreenW, CGFLOAT_MIN))];
    
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    // tableHeaderView
    UIView *tableHeader = [[UIView alloc] init];
    tableHeader.frame = CGRectMake(0, 0, tableView.width, 30);
    tableView.tableHeaderView = tableHeader;
    
    UIView *containerV = [[UIView alloc] init];
    containerV.backgroundColor = JKGlobalBgColor;
    containerV.frame = tableHeader.bounds;
    [tableHeader addSubview:containerV];
    self.headerContainerView = containerV;
    
    // tableHeaderView上的label
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont systemFontOfSize:15];
    label.text = @"主编";
    [label sizeToFit];
    label.x = 15;
    label.centerY = tableHeader.centerY;
    [containerV addSubview:label];
    self.headerLabel = label;
    
    // tableHeaderView右边的箭头
    UIImageView *arrowImgV = [[UIImageView alloc] init];
    arrowImgV.tag = 100;
    arrowImgV.size = CGSizeMake(tableHeader.height, tableHeader.height);
    arrowImgV.x = JKScreenW - arrowImgV.width;
    arrowImgV.centerY = label.centerY;
    arrowImgV.image = [UIImage imageNamed:@"Home_Arrow"];
    [containerV addSubview:arrowImgV];
    
    // tableHeaderView底部分割线
    UIView *separator = [[UIView alloc] init];
    separator.frame = CGRectMake(0, tableHeader.height, tableHeader.width, 0.5);
    separator.backgroundColor = JKSameRGBColor(217);
    [containerV addSubview:separator];
    
    [self.headerContainerView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTableHeader)]];
}

// 点击tableHeaderView
- (void)tapTableHeader{
    ThemeEditorsViewController *vc = [[ThemeEditorsViewController alloc] init];
    vc.editors = self.editors;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setupTopImageView{
    
    UIImageView *topImageContainerViewView = [[UIImageView alloc] init];
    topImageContainerViewView.image = [UIImage imageNamed:@"Home_Image_Mask_Plus"];
    topImageContainerViewView.frame = CGRectMake(0, - (self.topImageH - JKNavBarHeight) * 0.5, self.view.width, self.topImageH);
    [self.view insertSubview:topImageContainerViewView atIndex:0];
    self.topImageContainerViewView = topImageContainerViewView;
    
    UIImageView *topImageView = [[UIImageView alloc] init];
    topImageView.alpha = 0;
    topImageView.frame = topImageContainerViewView.bounds;
    [topImageContainerViewView insertSubview:topImageView atIndex:0];
    self.topImageView = topImageView;
    
    UIImageView *topCoverImageView = [[UIImageView alloc] init];
    topCoverImageView.frame = topImageView.bounds;
    [topImageView addSubview:topCoverImageView];
    self.topCoverImageView = topCoverImageView;
    
    UIImageView *vv = [[UIImageView alloc] init];
    vv.image = [UIImage imageNamed:@"Home_Image_Mask_Plus"];
    vv.frame = topImageContainerViewView.bounds;
    [topCoverImageView addSubview:vv];
}

// 设置刷新控件
- (void)setupRefresh{
    
    self.tableView.mj_header = [MJRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewLists)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreLists)];
    self.tableView.mj_footer.hidden = YES;
    
    [self loadNewLists];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    self.reloadBtn.frame = CGRectMake(20, 0, self.tableView.width - 40, JKScreenH);
}

#pragma mark - 加载数据
// 获取最新数据
- (void)loadNewLists{
    
    [[NetworkingTool sharedNetworkingTool].operationQueue cancelAllOperations];
    [self.tableView.mj_footer endRefreshing];
    self.tableView.mj_footer.hidden = self.stories.count <= 0;
    [self.refreshView beginAnimating];
    
    NSString *urlStr = [NSString stringWithFormat:@"theme/%d", self.themeModel.ID];
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id responseObj, NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        
        if (error) {
            self.reloadBtn.hidden = NO;
            return;
        }
        
        [self.reloadBtn removeFromSuperview];
        [self.refreshView stopAnimating];
        
        ThemeContentModel *contentModel = [ThemeContentModel mj_objectWithKeyValues:responseObj];
        self.contentModel = contentModel;
        
        NSArray *stories = [NewsListModel mj_objectArrayWithKeyValuesArray:self.contentModel.stories];
        
        if (self.stories.count > 0) {
            
            if ([stories.firstObject ID] == [self.stories.firstObject ID]) {
                return;
            }
        }
        
        [self.stories removeAllObjects];
        [self.editors removeAllObjects];
        
        [self.stories addObjectsFromArray:stories];
        
        [self.topImageView sd_setImageWithURL:[NSURL URLWithString:contentModel.image] placeholderImage:nil options:(SDWebImageAvoidAutoSetImage) completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
            if (image == nil) return;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                __weak typeof(self) weakSelf = self;
                
                [self.topCoverImageView setImageToBlur:image blurRadius:8 completionBlock:^{
                    
                    weakSelf.topImageView.image = image;
                    
                    [UIView animateWithDuration:0.5 animations:^{
                        
                        weakSelf.topImageView.alpha = 1;
                        
                    } completion:^(BOOL finished) {
                    }];
                }];
            });
        }];
        
        // 执行缓存
        [SQLiteManager cacheStoryLists:self.contentModel.stories date:@"0" isTop:NO isLatest:NO isMore:NO];
        
        NSArray *editors = [ThemeEditorModel mj_objectArrayWithKeyValuesArray:self.contentModel.editors];
        [self.editors addObjectsFromArray:editors];
        
        [self.tableView reloadData];
        
//        [UIView animateWithDuration:0.5 animations:^{
//
//        } completion:^(BOOL finished) {
//
//        }];
        
        // 循环添加主编头像
        for (int i = 0; i < self.editors.count; i++) {
            UIImageView *iconV = [[UIImageView alloc] init];
            iconV.size = CGSizeMake(18, 18);
            iconV.x = CGRectGetMaxX(self.headerLabel.frame) + 12 + (20 + 5) * i;
            iconV.centerY = self.headerContainerView.centerY;
            [iconV setHeaderIcon:[self.editors[i] avatar]];
            [self.headerContainerView addSubview:iconV];
        }
        
        self.tableView.mj_footer.hidden = NO;
        
        self.tableView.backgroundColor = nil;
    }];
}

// 加载更多数据
- (void)loadMoreLists{
    
    [[NetworkingTool sharedNetworkingTool].operationQueue cancelAllOperations];
    [self.tableView.mj_footer endRefreshing];
    
    NewsListModel *lastModel = self.stories.lastObject;
    NSString *urlStr = [NSString stringWithFormat:@"theme/%d/before/%d", self.themeModel.ID, lastModel.ID];
    
    [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id responseObj, NSError *error) {
        
        [self.tableView.mj_footer endRefreshing];
        
        if (error) return;
        
        NSArray *stories = [NewsListModel mj_objectArrayWithKeyValuesArray:responseObj[@"stories"]];
        [self.stories addObjectsFromArray:stories];
        
        [self.tableView reloadData];
        
        // 执行缓存
        [SQLiteManager cacheStoryLists:responseObj[@"stories"] date:@"0" isTop:NO isLatest:NO isMore:NO];
    }];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.stories.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ThemeCell *cell = [tableView dequeueReusableCellWithIdentifier:themeReuseID];
    
    NewsListModel *model = self.stories[indexPath.row];
    model.alreadyRead = [SQLiteManager queryIsReadWithStoryID:model.ID];
    cell.model = model;
    
    // 切换皮肤
    if ([self.currentSkinModel isEqualToString:JKNightSkinModelValue]) {
        [cell changeToNightSkin];
        
    }else{
        [cell changeToDaySkin];
    }
    
    return cell;
}

#pragma mark - <UITableViewDelegate>
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NewsListModel *model = self.stories[indexPath.row];
    NewsDetailViewController *detailVc = [[NewsDetailViewController alloc] init];
    detailVc.storyID = model.ID;
    detailVc.backgroundImageUrl = self.contentModel.background;
    detailVc.themeStories = self.stories;
    detailVc.stories = nil;
    detailVc.indexPath = indexPath;
    detailVc.storyListVc = self;
    
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y > 0) {
        self.refreshView.progress = 0;
        self.topCoverImageView.alpha = 1;
        return;
    }
    
    self.topCoverImageView.alpha = scrollView.contentOffset.y / (self.topImageH - JKNavBarHeight) + 1;
    
    // 刷新控件的进度
    self.refreshView.progress = -scrollView.contentOffset.y / 54.0;
    
    self.topImageContainerViewView.y = -(self.topImageH - JKNavBarHeight) * 0.5 - scrollView.contentOffset.y * 0.5;
    
    scrollView.contentOffset = (-scrollView.contentOffset.y >= (self.topImageH - JKNavBarHeight)) ? CGPointMake(0, -self.topImageH + JKNavBarHeight) : CGPointMake(0, scrollView.contentOffset.y);
}

- (void)reloadReadStoryWithIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationNone)];
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    
    if ([self.currentSkinModel isEqualToString:currentSkinModel]) {
        return;
    }
    
    self.currentSkinModel = currentSkinModel;
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        
        self.view.backgroundColor = JKNightSkinColor;
        self.headerContainerView.backgroundColor = self.view.backgroundColor;
        self.headerLabel.textColor = JKColor(128, 128, 128);
        
        for (ThemeCell *cell in self.tableView.visibleCells) {
            
            [cell changeToNightSkin];
        }
        
    }else{ // 日间模式
        
        self.view.backgroundColor = JKGlobalBgColor;
        self.headerContainerView.backgroundColor = self.view.backgroundColor;
        self.headerLabel.textColor = JKColor(96, 96, 96);
        
        for (ThemeCell *cell in self.tableView.visibleCells) {
            
            [cell changeToDaySkin];
        }
    }
    
    self.tableView.backgroundColor = self.stories.count > 0 ? nil : self.view.backgroundColor;
}
@end
